package Demo530;

import java.sql.*;
import java.util.Scanner;

public class Register {
    private static final String URL = "jdbc:mysql://localhost:3306/userdb?useSSL=false&serverTimezone=UTC";
    private static final String username = "root";
    private static final String password = "123456";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void addEmployee(Employee employee) {
        String sql = "INSERT INTO user (username, password, age) VALUES (?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(URL, username, password);
             PreparedStatement pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {

            pstmt.setString(1, employee.getUsername());
            pstmt.setString(2, employee.getPassword());
            pstmt.setInt(3, employee.getAge());

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        employee.setId(generatedKeys.getInt(1));
                        System.out.println("员工信息已成功插入，ID：" + employee.getId());
                    }
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入员工姓名：");
        String name = scanner.nextLine();

        System.out.print("请输入员工密码：");
        String pwd = scanner.nextLine();

        System.out.print("请输入员工年龄：");
        int age = Integer.parseInt(scanner.nextLine());

        Employee emp = new Employee(name, pwd, age);
        addEmployee(emp);

        scanner.close();
    }
}